<template>
  <div class="detail">
    <!-- 主图轮播 -->
    <div class="swiper-container">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item
          v-for="photo in mainPhoto"
          :key="photo.id"
        >
          <img v-lazy="photo.url" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <!-- 商品标题、价格、描述 -->

    <!-- 分隔线 -->
    <van-divider>商品图文详情</van-divider>

    <!-- 图文详情 -->
    <div class="detail-content">
      <img
        v-for="item in detailImgs"
        :key="item.image.id"
        v-lazy="item.image.url" />
    </div>

    <!-- tabbar -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot />
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="total" @click="jumpToCart" />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="12" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addToCartHandler" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import { getDetail } from '@/api/detail'
export default {
  name: 'Detail',
  data () {
    return {
      mainPhoto: [],
      detailImgs: [],
      detail: {}
    }
  },
  computed: {
    total () {
      return this.$store.getters.totalCount
    }
  },
  created () {
    console.log('detail:', this)
    // 加载详情页面数据
    getDetail(this.$route.params.id)
      .then(res => {
        console.log('响应数据：', res)
        // 主图
        this.mainPhoto = res.photo
        // 图文详情
        this.detailImgs = res.descContentList.filter(item => item.photo)
        // 商品详情数据
        // this.detail = res
      })
  },
  methods: {
    jumpToCart () {
      this.$router.push('/cart')
    },
    // 加入购物车处理
    addToCartHandler () {
      const { id, title, thumbnail, price } = this.detail
      // 构建当前选购商品的信息
      const payload = {
        id,
        title,
        desc: title,
        img: thumbnail,
        amount: 1,
        price
      }
      // 调用 store.commit() 提交 mutation
      // 注意：不能直接调用 mutation handler(.addToCart()方法)
      // commit('mutation方法名', 额外参数)
      this.$store.commit('addToCart', payload)
    }
  }
}
</script>

<style lang="scss" scoped>
  .swiper-container {
    width: 100%;
    height: 0;
    padding-top: 100%;
    position: relative;
  }
  .my-swipe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;

    .van-swipe-item {
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .detail-content {
    width: 100%;
    img {
      width: 100%;
      display: block;
    }
  }
</style>
